iT邦幫忙

2022 iThome 鐵人賽

DAY 3
0
Mobile Development

iOS菜逼八連續30天挑戰-2系列 第 3

iOS菜逼八連續30天挑戰-2 UIBlurEffect

  • 分享至 

  • xImage
  •  

今天簡單介紹實現iphone背景霧化,也就是毛玻璃效果,蠻簡單的。
程式碼:

let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.systemMaterialDark)
let blurView = UIVisualEffectView(effect: blurEffect)
blurView.frame.size = CGSize(width: self.view.frame.width, height: self.view.frame.height)
self.view.addSubview(blurView)

這邊可以去設定你要想要的模糊效果

如果想要取消透明效果,可以直接把他隱藏起來,這裡有程式碼可以參考:

//
//  ViewController.swift
//  test
//
//  Created by Wang Allen on 2022/9/14.
//

import UIKit

class ViewController: UIViewController {
    let button = UIButton()   //顯示毛玻璃效果的btn
    let cancelbtn = UIButton() //取消毛玻璃效果的btn
    var ifBlurEfectViewisHidden = true //判斷毛玻璃是否隱藏
    var blurView = UIVisualEffectView()

    override func viewDidLoad() {
        super.viewDidLoad()
        button.frame = CGRect(x: 200, y: 200, width: 150, height: 50)
        let fullScrenSize = UIScreen.main.bounds
        button.center = CGPoint(x: fullScrenSize.width * 0.5, y: fullScrenSize.height * 0.5)
        self.button.backgroundColor = .black
        self.button.setTitle("開啟毛玻璃效果", for: .normal)
        self.view.addSubview(button)
        button.addTarget(self, action: #selector(categoryBtnPress), for: .touchUpInside)
        let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.systemMaterialDark)
        blurView = UIVisualEffectView(effect: blurEffect)
        blurView.frame.size = CGSize(width: self.view.frame.width, height: self.view.frame.height)
        self.view.addSubview(blurView)
        cancelbtn.frame = CGRect(x: 200, y: 200, width: 150, height: 50)
        cancelbtn.center = CGPoint(x: fullScrenSize.width * 0.5, y: fullScrenSize.height * 0.4)
        self.cancelbtn.backgroundColor = .red
        self.cancelbtn.setTitle("關閉毛玻璃效果", for: .normal)
        self.view.addSubview(cancelbtn)
        cancelbtn.addTarget(self, action: #selector(cancelBlurEffect), for: .touchUpInside)
        cancelbtn.isHidden = true
        blurView.isHidden = true

    }
    @objc func categoryBtnPress(){

        
        if ifBlurEfectViewisHidden {
            blurView.isHidden = false
            cancelbtn.isHidden = false
            print("show")

        }
        ifBlurEfectViewisHidden = !ifBlurEfectViewisHidden

    }
    @objc func cancelBlurEffect(){
        if !ifBlurEfectViewisHidden{
            blurView.isHidden = true
            print("hide")
            cancelbtn.isHidden = true
        }
        ifBlurEfectViewisHidden = true

    }

}


UI我就不多講,比較值得注意的是,毛玻璃雖然是半透明的,但他等於是蓋一塊view上去,所以底下的btn是沒辦法再按的,所以我選擇在建立毛玻璃的時候,在他上層蓋一個btn讓他取消效果~


上一篇
iOS菜逼八連續30天挑戰-2 ScrollView(2/2)
下一篇
iOS菜逼八連續30天挑戰-2 CGRect、CGPoint、Frame、Bounds
系列文
iOS菜逼八連續30天挑戰-230
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言